/**
 * Copyright (c) 2024,  科泰集团教研团队
 * 版权所有，请勿侵权
 */
package com.ktjiaoyu.ktmall.dao.impl;
import com.ktjiaoyu.ktmall.dao.BaseDao;
import com.ktjiaoyu.ktmall.dao.AdminUserDao;
import com.ktjiaoyu.ktmall.entity.AdminUser;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
 * 管理员信息表，用于登录后台
 * @author 科泰集团教研团队
 * @createTime 2024-4-9 17:36:33
 * @lastModify 2024-4-9 17:36:33
 * @version 1.0.0
 */
public class AdminUserDaoImpl extends BaseDao implements AdminUserDao {

    @Override
    public AdminUser getByUsername(String username) {
        String sql = "select * from kt_admin_user where username=?";
        try {
            List<AdminUser> list = executeQuery(sql, rs -> {
                List<AdminUser> l = new ArrayList<>();
                try {
                    while (rs.next()) {
                        l.add(extractAdminUser(rs));
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return l;
            }, username);
            return list.isEmpty() ? null : list.get(0);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<AdminUser> getPage(AdminUser entity, Integer pageNo, Integer pageSize) {
        StringBuilder sql = new StringBuilder("select * from kt_admin_user where 1=1 ");
        List<Object> params = new ArrayList<>();
        if(entity != null){
            if(entity.getId() != null){ sql.append(" and id = ?"); params.add(entity.getId()); }
            if(entity.getUsername() != null){ sql.append(" and username = ?"); params.add(entity.getUsername()); }
            if(entity.getPassword() != null){ sql.append(" and password = ?"); params.add(entity.getPassword()); }
            if(entity.getNickname() != null){ sql.append(" and nickname = ?"); params.add(entity.getNickname()); }
        }
        sql.append(" limit ?, ?");
        params.add((pageNo - 1) * pageSize);
        params.add(pageSize);
        try {
            return executeQuery(sql.toString(), rs -> {
                List<AdminUser> list = new ArrayList<>();
                try {
                    while (rs.next()) {
                        list.add(extractAdminUser(rs));
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return list;
            }, params.toArray());
        } catch (SQLException e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    @Override
    public int count(AdminUser entity) {
        StringBuilder sql = new StringBuilder("select count(1) from kt_admin_user where 1=1 ");
        List<Object> params = new ArrayList<>();
        if(entity != null){
            if(entity.getId() != null){ sql.append(" and id = ?"); params.add(entity.getId()); }
            if(entity.getUsername() != null){ sql.append(" and username = ?"); params.add(entity.getUsername()); }
            if(entity.getPassword() != null){ sql.append(" and password = ?"); params.add(entity.getPassword()); }
            if(entity.getNickname() != null){ sql.append(" and nickname = ?"); params.add(entity.getNickname()); }
        }
        try {
            List<Integer> result = executeQuery(sql.toString(), rs -> {
                List<Integer> l = new ArrayList<>();
                try {
                    if (rs.next()) {
                        l.add(rs.getInt(1));
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return l;
            }, params.toArray());
            return result.isEmpty() ? 0 : result.get(0);
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public List<AdminUser> getAll() {
        String sql = "select * from kt_admin_user";
        try {
            return executeQuery(sql, rs -> {
                List<AdminUser> list = new ArrayList<>();
                try {
                    while (rs.next()) {
                        list.add(extractAdminUser(rs));
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return list;
            });
        } catch (SQLException e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    @Override
    public AdminUser getById(Long id) {
        String sql = "select * from kt_admin_user where id=?";
        try {
            List<AdminUser> list = executeQuery(sql, rs -> {
                List<AdminUser> l = new ArrayList<>();
                try {
                    while (rs.next()) {
                        l.add(extractAdminUser(rs));
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return l;
            }, id);
            return list.isEmpty() ? null : list.get(0);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public int insert(AdminUser entity) throws SQLException {
        return executeUpdate("INSERT INTO kt_admin_user(`username`,`password`,`nickname`) VALUES (?,?,?);", entity.getUsername(), entity.getPassword(), entity.getNickname());
    }

    @Override
    public int[] insertBatch(AdminUser... entities) {
        int[] rows = null;
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            conn.setAutoCommit(false);
            String sql = "INSERT INTO kt_admin_user(`username`,`password`,`nickname`) VALUES (?,?,?);";
            stmt = conn.prepareStatement(sql);
            for (AdminUser entity : entities) {
                if(entity == null){
                    continue;
                }
                int j = 1;
                stmt.setObject(j++, entity.getUsername());
                stmt.setObject(j++, entity.getPassword());
                stmt.setObject(j++, entity.getNickname());
                stmt.addBatch();
            }
            rows = stmt.executeBatch();
            stmt.clearBatch();
            conn.commit();
        }catch (Exception e){
            e.printStackTrace();
            if(conn != null){
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }
        return rows;
    }

    @Override
    public int update(AdminUser entity) {
        if(entity == null || entity.getId() == null){
            return 0;
        }
        List<Object> params = new ArrayList<>();
        StringBuilder sql = new StringBuilder("UPDATE `kt_admin_user` SET ");
        if(entity.getUsername() != null && !entity.getUsername().trim().isEmpty()){
            sql.append(" username = ? ,");
            params.add(entity.getUsername());
        }
        if(entity.getPassword() != null && !entity.getPassword().trim().isEmpty()){
            sql.append(" password = ? ,");
            params.add(entity.getPassword());
        }
        if(entity.getNickname() != null && !entity.getNickname().trim().isEmpty()){
            sql.append(" nickname = ? ,");
            params.add(entity.getNickname());
        }
        if(sql.lastIndexOf(",") == sql.length()-1){
            sql.deleteCharAt(sql.length()-1);
        }
        sql.append(" WHERE id = ?");
        params.add(entity.getId());
        try {
            return executeUpdate(sql.toString(), params.toArray());
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int deleteByEntity(AdminUser entity)  {
        if(entity == null || entity.getId() == null){
            return 0;
        }
        return deleteById(entity.getId());
    }

    @Override
    public int deleteById(Long id) {
        String sql = "DELETE FROM kt_admin_user WHERE id=?";
        try {
            return executeUpdate(sql, id);
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int[] deleteBatch(Long... ids) {
        int[] rows = null;
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            conn.setAutoCommit(false);
            String sql = "DELETE FROM kt_admin_user WHERE id=?";
            stmt = conn.prepareStatement(sql);
            for (Long id : ids) {
                if(id == null){
                    continue;
                }
                stmt.setObject(1, id);
                stmt.addBatch();
            }
            rows = stmt.executeBatch();
            stmt.clearBatch();
            conn.commit();
        }catch (Exception e){
            e.printStackTrace();
            if(conn != null){
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }
        return rows;
    }

    private AdminUser extractAdminUser(ResultSet rs) throws SQLException {
        AdminUser adminUser = new AdminUser();
        adminUser.setId(rs.getLong("id"));
        adminUser.setUsername(rs.getString("username"));
        adminUser.setPassword(rs.getString("password"));
        adminUser.setNickname(rs.getString("nickname"));
        return adminUser;
    }
}
